package com.zhang.second.day03;

import com.zhang.second.utils.IntegerSource;
import com.zhang.second.utils.IntegerStatistic;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 使用定时器对结果进行限流，每隔10s输出统计结果
 * @author: zhang
 * @date: 2022/1/30 19:27
 */
public class Example11 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerStatistic>() {
                    //声明状态变量
                    private ValueState<IntegerStatistic> accumulator;
                    private ValueState<Long> timerTs;

                    //初始化状态变量
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        accumulator = getRuntimeContext().getState(
                                new ValueStateDescriptor<IntegerStatistic>("acc", Types.POJO(IntegerStatistic.class))
                        );
                        timerTs = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>("timer-ts", Types.LONG)
                        );
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.Context ctx, Collector<IntegerStatistic> out) throws Exception {
                        if (accumulator.value() == null) {
                            accumulator.update(new IntegerStatistic(
                                    value,
                                    value,
                                    value,
                                    1,
                                    value
                            ));
                        } else {
                            IntegerStatistic tmp = accumulator.value();
                            accumulator.update(new IntegerStatistic(
                                    Math.max(value, tmp.max),
                                    Math.min(value, tmp.min),
                                    value + tmp.sum,
                                    tmp.count + 1,
                                    (value + tmp.sum) / (tmp.count + 1)
                            ));
                        }

                        if (timerTs.value() == null) {
                            //获取当前时间戳
                            long currTs = ctx.timerService().currentProcessingTime();
                            long tenSecLater = currTs + 10 * 1000L;
                            //注册发送统计数据的定时器
                            ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                            //保存定时器状态
                            timerTs.update(tenSecLater);
                        }

                    }

                    //定时器用来向下游发送统计数据
                    //只有定时器触发执行，才能这册新的定时器
                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.OnTimerContext ctx, Collector<IntegerStatistic> out) throws Exception {
                        //向下游发送数据
                        out.collect(accumulator.value());
                        timerTs.clear();
                    }
                })
                .print();

        env.execute();
    }
}
